package sample;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
public class Mqtts {
    private static Mqtts ourInstance = new Mqtts();
    @Getter
    private MqttClient mqttClient;

    public static Mqtts getInstance() {
        return ourInstance;
    }

    private Mqtts() {
    }

    public boolean connect(String host, String port, String username,String password) throws MqttException {
        String serverURI = String.format("tcp://%s:%s", host, port);
        String clientId = "mqtt_carPark:" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        MqttClient mqttClient = new MqttClient(serverURI, clientId, new MemoryPersistence());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        options.setConnectionTimeout(5);
        options.setKeepAliveInterval(5);
        log.info("mqtt连接地址:{}",serverURI);
        log.info("mqtt客户端id:{}",clientId);
        log.info("mqtt连接参数:{}",options);
        mqttClient.connect(options);
        if(mqttClient.isConnected()){
            this.mqttClient = mqttClient;
        }
        return mqttClient.isConnected();
    }
}
